package com.prodog.gamemodule.fight.damage.handler.impl;

import cn.hutool.core.util.ReflectUtil;
import com.prodog.commonmodule.prop.entity.ObjProp;
import com.prodog.gamemodule.fight.damage.entity.Damage;
import com.prodog.gamemodule.fight.action.entity.AtkActionRes;
import com.prodog.gamemodule.fight.damage.entity.ElementalProp;
import com.prodog.gamemodule.fight.damage.handler.DamageHandler;
import com.prodog.gamemodule.fight.fightobj.entity.FightObj;
import com.prodog.gamemodule.fight.fightobj.entity.FightSkill;

import java.util.*;
import java.util.stream.Collectors;

/***
 * 属性伤害
 */
public class ElementalDamageHandler implements DamageHandler {
    private FightObj obj;
    private FightObj beActedObj;
    private AtkActionRes atkActionRes;

    public ElementalDamageHandler(FightObj obj, FightObj beActedObj, AtkActionRes atkActionRes) {
        this.obj = obj;
        this.beActedObj = beActedObj;
        this.atkActionRes = atkActionRes;
    }

    @Override
    public void handle() {
        FightSkill skill = obj.getSkills().get(obj.getAction().getActionId());
        ObjProp prop = obj.getFightProp();
        Damage normalDamage = atkActionRes.getDamage(beActedObj.getUuid(), Damage.NORMAL);
        long damage = normalDamage.getValue();
        //获取攻击的属性
        Set<String> elemental = new LinkedHashSet<>();
        elemental.addAll(skill.getElemental());
        if (!skill.isIgnoreObjElemental()) {
            elemental.addAll(prop.getElemental());
        }
        //取这些属性当中的最高属性攻击
        if (elemental.size() > 0) {
            ArrayList<ElementalProp> eleProps = new ArrayList<>();
            for (String ele : elemental) {
                ElementalProp eleProp = new ElementalProp(ele, (Integer) ReflectUtil.getFieldValue(prop, ele + "Attack"));
                eleProps.add(eleProp);
            }
            List<ElementalProp> sorted = eleProps.stream()
                    .sorted(Comparator.comparing(ElementalProp::getValue).reversed())
                    .collect(Collectors.toList());
            ElementalProp maxProp = sorted.get(0);
            Integer resistance = (Integer) ReflectUtil.getFieldValue(prop, maxProp.getElemental() + "Resistance");
            Integer finalAtk = maxProp.getValue() - resistance < 0 ? 0 : maxProp.getValue() - resistance;
            long eleDamage = (long) ((damage * finalAtk) * 0.01);
            String damageName = "ELEMENTAL_" + maxProp.getElemental().toUpperCase();
            atkActionRes.addDamage(beActedObj.getUuid(), new Damage() {{
                setByUuid(obj.getUuid());
                setDamageType(skill.getDamageType());
                setName(damageName);
                setAffectType(skill.getAffectType());
                setValue(eleDamage);
            }});
        }
    }
}
